package com.alibaba.nacos.config.server.jpa.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.model.User;
import com.alibaba.nacos.config.server.jpa.entity.UsersEntity;
import com.alibaba.nacos.config.server.jpa.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * The type of nacos-all.
 *
 * @author 问道于盲
 * @date 2020-03-11
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class UserPersistServiceImpl {

    @Autowired
    private UsersRepository usersRepository;

    public void createUser(String username, String password) {
        UsersEntity data = new UsersEntity();
        data.setUsername(username);
        data.setPassword(password);
        data.setEnabled(true);
        usersRepository.save(data);
    }

    public void deleteUser(String username) {
        usersRepository.deleteByUsername(username);
    }

    public void updateUserPassword(String username, String password) {
        UsersEntity user = usersRepository.findByUsername(username);
        if (user == null){
            return;
        }
        user.setPassword(password);
        usersRepository.save(user);

    }

    public User findUserByUsername(String username) {
        UsersEntity user = usersRepository.findByUsername(username);
        if (user == null){
            return null;
        }
        return convert(user);
    }

    private User convert(UsersEntity user) {
        User data = new User();
        data.setPassword(user.getPassword());
        data.setUsername(user.getUsername());
        return data;
    }

    public Page<User> getUsers(int pageNo, int pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNo-1, pageSize);
        org.springframework.data.domain.Page<UsersEntity> datas = usersRepository.findAll(pageRequest);
        List<User> users = datas.stream().map(this::convert).collect(Collectors.toList());

        Page<User> page = new Page<>();
        page.setPageItems(users);
        page.setPageNumber(pageNo);
        page.setTotalCount((int)datas.getTotalElements());
        page.setPagesAvailable(datas.getTotalPages());
        return page;
    }
}
